package com.jiexin.common;

import com.jiexin.exception.ParamException;
import com.jiexin.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Jay_Liu
 * @Description: 异常处理类
 * @Date: Created in 11:22 2018/4/1 0001
 * @Modified By:
 */
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver{
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {

        //获取请求路径
        String url = httpServletRequest.getRequestURI();
        //返回格式
        ModelAndView mv;
        //默认不知道的异常
        String defaultMsg = "System error";
        //设计时，返回对象是JSON的,已.json后缀
        if(url.endsWith(".json")){
            if(ex instanceof PermissionException || ex instanceof ParamException){
                JsonData result = JsonData.fail(ex.getMessage());
                //1.jsonView 是spring-servlet中声明的json格式对象。
                //2.将返回对象定义成map格式进行返回
                mv = new ModelAndView("jsonView",result.toMap());
            }else{//.json结尾的其他异常
                log.error("unkown json exception, url:" + url, ex);
                JsonData result = JsonData.fail(defaultMsg);
                mv = new ModelAndView("jsonView", result.toMap());
            }
        }else if(url.endsWith(".page")){//返回页面的，以.page后缀
            log.error("unkown page exception, url:" + url, ex);
            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("exception", result.toMap());
        }else{//其他格式
            log.error("unkown exception, url:" + url, ex);
            JsonData result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("jsonView", result.toMap());
        }

        return mv;
    }
}
